<template>
	<view class="container">
		<steps 
			typeCode="ChuChai" 
			:brief="brief" 
			:notEmpty="checkBukaFiled" 
			:disabled="disabled"
			:checkResult="checkResult"
			:insflowid="insflowid"
			@confirm="confirm">
			<view class="container__list" style="padding: 10rpx 20rpx;">
				<view class="container__list--text">
					<text class="container__list--text-symbol">*</text>
					<text class="container__list--text-des">出差事由</text>
				</view>
				<view class="container__list--textarea">
					<input type="text" v-model="reason" placeholder="请输入出差事由" placeholder-style="font-size: 27rpx;color: #aaa;" />
				</view>
			</view>
			<view class="container__list" style="padding: 10rpx 20rpx;display: flex;justify-content: space-between;">
				<view class="container__list--text">
					<text class="container__list--text-symbol">*</text>
					<text class="container__list--text-des">交通工具</text>
				</view>
				<view class="container__list--right" style="width: 400rpx;">
					<u-subsection :list="trafficTools" :current="trafficIndex" @change="trafficToolsChange"></u-subsection>
				</view>
			</view>
			<view class="container__list" style="padding: 10rpx 20rpx;display: flex;justify-content: space-between;margin-top: 0;">
				<view class="container__list--text">
					<text class="container__list--text-des">单程往返</text>
				</view>
				<view class="container__list--right" style="width: 200rpx;">
					<u-subsection :list="trafficTypes" :current="typeIndex" @change="trafficTypesChange"></u-subsection>
				</view>
			</view>
			<view class="container__list" style="margin-top: 0;">
				<view class="hover" hover-class="clickable">
					<view class="container__list--text">
						<text class="container__list--text-des">出发城市</text>
					</view>
					<view class="container__list--time">
						<view class="container__list--time-text" @click="goSelectCityPage('outer-from-city')">
							<text v-if="!fromCity">请选择</text>
							<text v-else>{{fromCity}}</text>
						</view>
					</view>
					<view class="container__list--icon">
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="container__list" style="margin-top: 0;">
				<view class="hover" hover-class="clickable">
					<view class="container__list--text">
						<text class="container__list--text-des">目的城市</text>
					</view>
					<view class="container__list--time">
						<view class="container__list--time-text" @click="goSelectCityPage('outer-to-city')">
							<text v-if="!toCity">请选择</text>
							<text v-else>{{toCity}}</text>
						</view>
					</view>
					<view class="container__list--icon">
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="container__list" style="margin-top: 0;">
				<view class="hover" hover-class="clickable">
					<view class="container__list--text">
						<text class="container__list--text-symbol">*</text>
						<text class="container__list--text-des">开始时间</text>
					</view>
					<view class="container__list--time">
						<view class="container__list--time-text" @click="startShow">
							<text v-if="!startDateTime">请选择</text>
							<text v-else>{{startDateTime}}</text>
						</view>
					</view>
					<view class="container__list--icon">
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="container__list" style="margin-top: 0;">
				<view class="hover" hover-class="clickable">
					<view class="container__list--text">
						<text class="container__list--text-symbol">*</text>
						<text class="container__list--text-des">结束时间</text>
					</view>
					<view class="container__list--time">
						<view class="container__list--time-text" @click="endShow">
							<text v-if="!endDateTime">请选择</text>
							<text v-else>{{endDateTime}}</text>
						</view>
					</view>
					<view class="container__list--icon">
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
				</view>
			</view>
			<view class="container__list" style="padding: 10rpx 20rpx;">
				<view class="container__list--text">
					<text class="container__list--text-des">出差天数</text>
				</view>
				<view class="container__list--textarea">
					<input type="number" v-model="hours" disabled @blur="checkDays"/>
				</view>
			</view>
			<view class="container__list" style="padding: 10rpx 20rpx;">
				<view class="container__list--text">
					<text class="container__list--text-des">出差备注</text>
				</view>
				<view class="container__list--textarea">
					<input type="text" v-model="remarks" placeholder="请输入" placeholder-style="font-size: 27rpx;color: #aaa;" />
				</view>
			</view>
		</steps>
		<datetime-picker ref="startDateTime" type="datetime" :border="false" returnType="date" v-model="startTime" hide-second @change="confirmStartDateTime" />
		<datetime-picker ref="endDateTime" type="datetime" :border="false" returnType="date" v-model="endTime" hide-second @change="confirmEndDateTime" />
	</view>
</template>

<script>
	import Steps from '@/pages/home/child/add-attend-apply/components/steps.vue'
	import _custom from '@/common/_custom.js'
	import _data from '@/common/_data.js'
	import moment from 'moment'
	import DatetimePicker from '@/components/custom/datetime-picker/uni-datetime-picker.vue'
	
	let flag = false;
	export default {
		components: {
			Steps,
			DatetimePicker
		},
		data() {
			return {
				obsusername: _data.localData('name'),
				pxid: _data.localData('userid'),
				static_avator: _data.data('static_url'),
				startTime: '',//弹窗显示的开始时间
				endTime: '',//弹窗显示的结束时间
				startDateTime: '',//表单显示的开始时间
				endDateTime: '',//表单显示的结束时间
				reason: '',//事由
				remarks: '',//备注
				hours: 0,//出差天数
				disabled: true,//是否校验通过
				checkResult: '',//校验结果
				data: {},//页面传递的数据
				insflowid: '',
				trafficTools: [
					{
						name: '飞机',
					}, 
					{
						name: '火车',
					}, 
					{
						name: '汽车',
					},
					{
						name: '其他',
					},
				],
				trafficIndex: 0,//交通工具索引
				trafficTypes: [
					{
						name: '单程',
					}, 
					{
						name: '往返',
					},
				],
				typeIndex: 0,//单程往返索引
				fromCity: '',//出发城市
				toCity: '',//目的城市
				dates: []
			}
		},
		onLoad(options) {
			let that = this;
			if(options.data) {
				this.data = JSON.parse(options.data)
				this.insflowid = options.insflowid;
				this.startDateTime = this.data.StartTime;
				this.startTime = this.data.StartTime;
				this.endDateTime = this.data.EndTime;
				this.endTime = this.data.EndTime;
				this.hours = this.data.TravelDays;
				this.reason = this.data.Reason;
				this.remarks = this.data.Remarks;
				this.fromCity = this.data.FromCity;
				this.toCity = this.data.ToCity;
				this.trafficTools.forEach((item,index) => {
					if(item.name == this.data.TravelTool) this.trafficIndex = index
				})
				this.trafficTypes.forEach((item,index) => {
					if(item.name == this.data.TravelType) this.typeIndex = index
				})
				this.checkForm();
				return
			}
			_data.localData('select-list-outer',[]);
		},
		onShow() {
			if(Object.keys(this.data).length && !flag) {
				flag = true;
				return;
			}
			
			let id = _data.localData('select-city-id');
			let selectCity = _data.localData('select-city');
			id == 'outer-from-city' ? this.fromCity = selectCity : this.toCity = selectCity;
		},
		onUnload() {
			flag = false;
			_data.localData('select-list-outer',[]);
			_data.localData('select-city-id','');
			_data.localData('select-city','');
		},
		computed: {
			brief() {
				return  '出差事由：' + this.reason + '|开始时间：' + this.startDateTime + '|结束时间：' + this.endDateTime + '|出差天数：' + this.hours
			},
			checkBukaFiled() {
				return this.reason && this.startDateTime && this.endDateTime ? true : false;
			},
		},
		methods: {
			startShow() {
				this.startTime = this.startTime ? moment(this.startTime).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm') + ':00'
				this.startDateTime = this.startTime;
				this.checkForm();
				this.$refs.startDateTime.show()
			},
			endShow() {
				this.endTime = this.endTime ? moment(this.endTime).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm') + ':00'
				this.endDateTime = this.endTime;
				this.checkForm();
				this.$refs.endDateTime.show()
			},
			confirmStartDateTime(e) {
				this.startDateTime = moment(e).format('YYYY-MM-DD HH:mm:ss');
				this.checkForm();
			},
			confirmEndDateTime(e) {
				this.endDateTime = moment(e).format('YYYY-MM-DD HH:mm:ss');
				this.checkForm();
			},
			/**
			 * 校验出差天数
			 * @param {Object} apiparam
			 */
			checkDays(e) {
				this.hours = e.detail.value;
				this.checkForm();
			},
			/**
			 * 表单校验
			 */
			checkForm() {
				if(!this.startDateTime || !this.endDateTime) return
				this.dates = [];
				let secondDiff = moment(this.endDateTime).diff(this.startDateTime,'second');
				if(secondDiff <= 0) {
					this.checkResult = '结束时间不得早于或等于开始时间';
					this.disabled = true;
					return
				}
				//开始时间和结束时间的间隔天数
				let day = 0;//出差天数
				let sDate = moment(this.startDateTime).format('YYYY-MM-DD');
				let eDate = moment(this.endDateTime).format('YYYY-MM-DD');
				let dayDiff = moment(eDate).diff(sDate,'day');
				let dates = [];
				if(dayDiff == 0) {//同一天
					let time = sDate + ' 12:00:00';
					let startDiff = moment(this.startDateTime).diff(time,'second');
					let endDiff = moment(this.endDateTime).diff(time,'second');
					if(startDiff < 0 && endDiff > 0) {//一整天
						day = 1;
					} else {//上午半天或下午半天
						day = 0.5;
					}
					dates = [{
						date: sDate,
						day: day
					}]
				} else {//不同天
					let startTime = sDate + ' 12:00:00';
					let endTime = eDate + ' 12:00:00';
					let startDayDiff = moment(this.startDateTime).diff(startTime,'second');
					let endDayDiff = moment(this.endDateTime).diff(endTime,'second');
					let startDay = startDayDiff >= 0 ? 0.5 : 1;//开始日期为上午则是1，下午则是0.5
					let endDay = endDayDiff < 0 ? 0.5 : 1;//结束日期为上午则是0.5，下午则是1
					day = startDay + endDay + (dayDiff - 1);
					let date = this.enumerateDaysBetweenDates(sDate,eDate);
					date.forEach(item => {
						if(item == sDate) {
							dates.push({
								date: item,
								day: startDay
							})
						} else if(item == eDate) {
							dates.push({
								date: item,
								day: endDay
							})
						} else {
							dates.push({
								date: item,
								day: 1
							})
						}
					})
				}
				this.hours = day;
				this.disabled = false;
				this.dates = dates;
			},
			/**
			 * 获取两个日期之间的所有日期(已经保证了startDate 小于endDate，且二者不相等)
			 * @param {Object} startDate
			 * @param {Object} endDate
			 */
			enumerateDaysBetweenDates(startDate, endDate) {
				let daysList = [];
				let SDate = moment(startDate);
				let EDate = moment(endDate);
				daysList.push(SDate.format("YYYY-MM-DD"));
				while(SDate.add(1,"days").isBefore(EDate)){    
					daysList.push(SDate.format("YYYY-MM-DD"));
				}
				daysList.push(EDate.format("YYYY-MM-DD"));
				return daysList;
			},
			/**
			 * 添加出差申请
			 * @param {Object} apiparam  接口参数
			 */
			outerAttendApply(apiparam) {
				return new Promise((resolve,reject) => {
					_custom.getDataJava({
						apiname: 'outerAttendApply',
						code: 3,
						apiparam,
						success(res) {
							resolve()
						}
					})
				})
			},
			/**
			 * 触发流程环节通知
			 */
			trigFlowStepNotice(apiparam) {
				let that = this;
				return new Promise((resolve,reject) => {
					_custom.getDataJava({
						apiname: 'trigFlowStepNotice',
						code: 2,
						apiparam,
						success() {
							resolve()
						}
					})
				})
			},
			/**
			 * 添加出差详情
			 * @param {Object} apiparam
			 */
			outerAttendDetail(apiparam) {
				return new Promise((resolve,reject) => {
					_custom.getDataJava({
						apiname: 'outerAttendDetail',
						code: 13,
						apiparam,
						success(res) {
							resolve()
						}
					})
				})
			},
			/**
			 * 点击提交按钮申请流程后的回调
			 * @param {Object} v 回调参数
			 */
			confirm(v) {
				this.outerAttendApply({
					obsusername: this.obsusername,
					insflowid: v.insflowid,
					reason: this.reason,
					traveltool: this.trafficTools[this.trafficIndex].name,
					traveltype: this.trafficTypes[this.typeIndex].name,
					fromcity: this.fromCity,
					tocity: this.toCity,
					starttime: this.startDateTime,
					endtime: this.endDateTime,
					traveldays: this.hours + '',
					remarks: this.remarks
				}).then(() => {
					let params = [];
					this.dates.forEach(value => {
						params.push({
							obsusername: this.obsusername,
							insflowid: v.insflowid,
							username: this.obsusername,
							pxid: this.pxid,
							outerdate: value.date,
							outerdays: value.day
						}) 
					})
					return this.outerAttendDetail(params)
				}).then(() =>{
					uni.showToast({
						title: '流程创建成功',
						icon: 'none'
					})
					this.trigFlowStepNotice({
						insflowid: v.insflowid,
					})
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/home/child/outer-attend/index?data=' + JSON.stringify(v)
						})
					},500)
				})
				
			},
			/**
			 * 切换交通工具
			 */
			trafficToolsChange(i) {
				this.trafficIndex = i;
			},
			/**
			 * 切换单程往返
			 */
			trafficTypesChange(i) {
				this.typeIndex = i;
			},
			/**
			 * 跳转到选择城市界面
			 */
			goSelectCityPage(v) {
				_data.localData('select-city-id',v);
				uni.navigateTo({
					url: '/pages/home/child/outer-attend-apply/city'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		overflow-x: hidden;
		padding-bottom: 90rpx;
		
		&__list {
			background-color: #fff;
			margin-top: 30rpx;
			position: relative;
			
			&--text {
				
				&-symbol {
					color: red;
					margin: 0 5rpx;
				}
				
				&-des {
					font-size: 30rpx;
				}
				
			}
			
			&--time {
				font-size: 32rpx;
				color: #aaa;
				margin-left: 20rpx;
				position: relative;
				height: 60rpx;
			}
			
			&--textarea {
				margin-left: 20rpx;
				font-size: 32rpx;
			}
			
			&--icon {
				position: absolute;
				right: 20rpx;
				top: 50%;
				transform: translateY(-50%);
				z-index: 9;
			}
			
			&--value {
				display: flex;
				
				&-user {
					margin-right: 20rpx;
				}
			}
		}
		
		&__detail {
			
			&--title {
				font-size: 27rpx;
				line-height: 60rpx;
				padding-left: 20rpx;
			}
			
			&--head,&--item {
				margin: 0 40rpx;
				margin-bottom: 20rpx;
				background-color: #fff;
				display: flex;
				align-items: center;
				border-radius: 5rpx;
				height: 80rpx;
				
				view {
					flex: 1;
					padding-left: 20rpx;
					font-size: 27rpx;
					
					&:first-child {
						border-right: 1rpx solid #eee;
					}
				}
			}
			
			&--item {
				color: #aaa;
				
			}
		}
		
	}
	
	.flex {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		box-sizing: border-box;
	}
	
	.hover {
		padding: 10rpx 20rpx;
	}
</style>
